package com.medvalley.tcm.controller;

import com.alibaba.fastjson.JSON;
import com.medvalley.tcm.domain.Questionnaire;
import com.medvalley.tcm.service.QuestionnaireService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by LinSong on 2018/3/6.
 */
@Controller
@ResponseBody
@Api(value = "体质辨识相关接口")
public class QuestionnaireController extends BaseController {

    @Autowired
    private QuestionnaireService questionnaireService;

    @ApiOperation(value = "校验条形码")
    @RequestMapping(value = "/questionnaire/barcode/check", method = RequestMethod.POST)
    public String check(@RequestParam("barcode") String barcode) {
        if (StringUtils.isEmpty(barcode)) {
            return JSON.toJSONString(error("条形码不能为空"));
        }
        boolean isReal = questionnaireService.checkBarcode(barcode);
        if (isReal) {
            return JSON.toJSONString(success());
        } else {
            return JSON.toJSONString(error("条形码错误"));
        }
    }

    /**
     * 提交问卷
     *
     * @param questionnaire
     * @return
     */
    @ApiOperation(value = "提交问卷")
    @RequestMapping(value = "/questionnaire/answer/save", method = RequestMethod.POST)
    public String save(@ModelAttribute Questionnaire questionnaire) {
        String result = questionnaireService.createQuestionnaire(questionnaire);
        return JSON.toJSONString(success(result));
    }

    /**
     * 根据机构和编号查询问卷分数
     *
     * @param userNumber
     * @param org
     * @return
     */
    @ApiOperation(value = "根据用户编号和机构号查询问卷")
    @RequestMapping(value = "/questionnaire/answer/detail", method = RequestMethod.POST)
    public String getByUserNumber(@RequestParam String userNumber, @RequestParam String org) {
        Questionnaire questionnaire = questionnaireService.getQuestionnaireByUserNumber(userNumber, org);
        return JSON.toJSONString(questionnaire);
    }

    @ApiOperation(value = "我的自检列表")
    @RequestMapping(value = "/questionnaire/myself/list", method = RequestMethod.POST)
    public String myselfQuestionnaire(@RequestParam(name = "edition", required = false, defaultValue = "-1") int edition, @RequestParam("phone") String phone,
                                      @RequestParam(name = "org", required = false, defaultValue = "hyg") String org,
                                      HttpServletRequest request) {
        if (StringUtils.isEmpty(phone)) {
            phone = getSessionPhone(request);
        }
        List<Questionnaire> questionnaireList = questionnaireService.findMyselfQuestionnaire(phone, edition, org);
        return JSON.toJSONString(success(questionnaireList));
    }

}
